/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function (nums) {
  let minArr = {}
  let v = nums.length - 2
  const getMinDataAndChange = index => {
    if (index === -1) {
      return -1
    }
    for (let i = index + 1; i < nums.length; i++) {
      if (nums[i] > nums[index]) {
        minArr[nums[i]] = i
      }
    }
    const minArrArr = Object.keys(minArr)
    if (minArrArr.length === 0) {
      return null
    }
    const minI = Math.min(...minArrArr)
    const j = minArr[minI]
    let tem = nums[j]
    nums[j] = nums[index]
    nums[index] = tem
    return index
  }
  while (true) {
    let data = getMinDataAndChange(v)

    if (data !== null) {
      if (data === -1) {
        nums = nums.sort((a, b) => a - b)
      } else {
        let sortArr = []
        let time = 0
        for (let i = data + 1; i < nums.length; i++) {
          sortArr[time] = nums[i]
          time++
        }
        sortArr = sortArr.sort((a, b) => a - b)
        let numtime = 0
        for (let i = 0; i < sortArr.length; i++) {
          nums[data + 1 + numtime] = sortArr[i]
          numtime++
        }
      }

      return nums
    } else {
      v = v - 1
    }
  }
}

console.log(nextPermutation([1, 4, 3, 2]))
